package com.acumenvn.pent.GameServices;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Disposable;

public class MusicManager implements Disposable {
	private static final MusicManager instance = null;
	
	public static final MusicManager getInstance() {
		if(instance == null) {
			instance = new MusicManager();
		}
		return instance;
	}
	public enum PenMusic {

		private String _fileName;
		private Music _musicResource;
		
		private PenMusic(String fileName) {
			this._fileName = fileName;
		}
		
		public String getFileName() {
			return this._fileName;
		}
		
		public Music getMusicResource() {
			return this._musicResource;
		}
		
		public void setMusicResource(Music resource) {
			this._musicResource = resource;
		}
	}
	
	// Hold the music being play
	private PenMusic _musicBeingPlayed;
	
	// The Volume to be set on music
	private float _musicVolume = 1f;
	
	// music enable ?
	private boolean _musicEnable = true;
	
	// Constructor
	
	public MusicManager() {
		// TODO Auto-generated constructor stub
	} 
	
	// Play music
	
	public void playMusic(PenMusic m, Boolean loop) {
		// check if music is enable
		if(!_musicEnable) {
			return;
		}
		
		// check if m is being played
		if(this._musicBeingPlayed == m) {
			return;
		}
		
		// Stop music being played
		stopMusic();
		
		// start streaming the music
		FileHandle musicFile = Gdx.files.internal(m.getFileName());
		Music musicResource = Gdx.audio.newMusic(musicFile);
		musicResource.setVolume(this._musicVolume);
		musicResource.setLooping(loop);
		musicResource.play();
		
		// set the music being played
		this._musicBeingPlayed = m;
		this._musicBeingPlayed.setMusicResource(musicResource);
	}
	
	// Stop music being played
	public void stopMusic() {
		if(this._musicBeingPlayed != null) {
			Music musicResource = this._musicBeingPlayed.getMusicResource();
			musicResource.stop();
			musicResource.dispose();
			this._musicBeingPlayed = null;
		}
	}
	
	// Set volume
	public void setVolume(float vol) {
		if(vol < 0 || vol > 1) {
			throw new IllegalArgumentException( "The volume must be inside the range: [0,1]" );
			return;
		}
		
		this._musicVolume = vol;
		
		// if there is a music being played, so change it's volume
		if(this._musicBeingPlayed != null) {
			this._musicBeingPlayed.getMusicResource().setVolume(vol);
		}
	}
	
	// Enable or disable music
	
	public void setEnableMusic(Boolean on) {
		this._musicEnable = on;
		if(!this._musicEnable) {
			stopMusic();
		}
	}
	
	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		
	}
	
}
